package com.jack.netty.coder.tlv;

import com.jack.netty.message.Ping;
import com.jack.netty.message.Pong;
import com.jack.netty.message.UserMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Created by jack on 15/9/25.
 */
public class TLVEncoder extends MessageToByteEncoder {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf out) throws Exception {

        if(o instanceof Ping){
            out.writeInt(Ping.getInstance().getType());
        }else if(o instanceof Pong){
            out.writeInt(Pong.getInstance().getType());
        }else{
            String message = o.toString();

            byte[] bytes = message.getBytes("UTF-8");

            out.writeInt(UserMsg.type);
            out.writeInt(bytes.length);
            out.writeBytes(bytes);
        }

    }
}
